﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WmWebSystem.Models;
using WmWebSystem.Service;

namespace WmWebSystem.DbHelper
{
    public static class AttentionHelper
    {
        public static IEnumerable<Attention> FindAll() 
        {
            WmDb mydb = new WmDb();
            var atts = from a in mydb.Attentions
                        orderby a.AddTime descending
                        select a;
            return atts;
        }

        public static void AddNewFansToAttentions(string pno, string name)
        {
            WmDb mydb = new WmDb();

            DateTime time = DateTime.Now;
            string editor = HttpContext.Current.User.Identity.Name;
            Attention attention = new Attention();
            attention.ProjectNo = pno;
            attention.ProjectName = name;
            attention.AddTime = time;
            attention.Editor = editor;
            try
            {
                mydb.Attentions.Add(attention);
                mydb.SaveChanges();
                //将记录写入日志
                string p1 = "Add new to Attentions, The ProjectNo:" + pno;
                WriteLog.WriteSysLog(p1);
            }
            catch (FieldAccessException ex)
            {
                //失败，进行回滚操作  记录异常
                WriteLog.WriteSysLog(ex.ToString());
            }


        }

        public static IEnumerable<Project> FindByUserName(string name) 
        {
            WmDb mydb = new WmDb();
            var project = from a in mydb.Projects
                            from b in mydb.Attentions
                            where a.ProjectNo == b.ProjectNo
                            orderby a.AddTime descending
                            select a;
            return project;
        }

        public static int AttentionCount(string pno) 
        {
            WmDb mydb=new WmDb();
            int count = (from a in mydb.Attentions
                         where a.ProjectNo == pno
                         select a).Count();
            return count;
        } 
    }
}
